package com.vibrationkeyboard.app.service

import android.content.Intent
import android.util.Log
import com.google.android.gms.wearable.*
import com.google.gson.Gson
import com.vibrationkeyboard.app.model.SensorData
import kotlinx.coroutines.*
import java.nio.charset.StandardCharsets

class WearDataLayerService : WearableListenerService() {

    private val gson = Gson()
    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    companion object {
        private const val TAG = "WearDataLayerService"
        private const val SENSOR_DATA_PATH = "/sensor_data"
        private const val RECOGNITION_RESULT_PATH = "/recognition_result"
        private const val COMMAND_PATH = "/command"
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "WearDataLayerService created")
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()
        Log.d(TAG, "WearDataLayerService destroyed")
    }

    override fun onDataChanged(dataEvents: DataEventBuffer) {
        Log.d(TAG, "onDataChanged: ${dataEvents.count} events")
        
        for (event in dataEvents) {
            if (event.type == DataEvent.TYPE_CHANGED) {
                val path = event.dataItem.uri.path
                when (path) {
                    SENSOR_DATA_PATH -> {
                        handleSensorData(event.dataItem)
                    }
                    RECOGNITION_RESULT_PATH -> {
                        handleRecognitionResult(event.dataItem)
                    }
                    COMMAND_PATH -> {
                        handleCommand(event.dataItem)
                    }
                }
            }
        }
    }

    override fun onMessageReceived(messageEvent: MessageEvent) {
        Log.d(TAG, "onMessageReceived: ${messageEvent.path}")
        
        when (messageEvent.path) {
            "/start_sensor" -> {
                startSensorService()
            }
            "/stop_sensor" -> {
                stopSensorService()
            }
            "/get_status" -> {
                sendStatus()
            }
        }
    }

    override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) {
        Log.d(TAG, "onCapabilityChanged: ${capabilityInfo.capabilities}")
    }

    private fun handleSensorData(dataItem: DataItem) {
        serviceScope.launch {
            try {
                val data = dataItem.data
                val jsonString = String(data, StandardCharsets.UTF_8)
                val sensorData = gson.fromJson(jsonString, SensorData::class.java)
                
                Log.d(TAG, "Received sensor data: $sensorData")
                
                // 处理传感器数据
                processSensorData(sensorData)
                
            } catch (e: Exception) {
                Log.e(TAG, "Error handling sensor data", e)
            }
        }
    }

    private fun handleRecognitionResult(dataItem: DataItem) {
        serviceScope.launch {
            try {
                val data = dataItem.data
                val result = String(data, StandardCharsets.UTF_8)
                
                Log.d(TAG, "Received recognition result: $result")
                
                // 处理识别结果
                processRecognitionResult(result)
                
            } catch (e: Exception) {
                Log.e(TAG, "Error handling recognition result", e)
            }
        }
    }

    private fun handleCommand(dataItem: DataItem) {
        serviceScope.launch {
            try {
                val data = dataItem.data
                val command = String(data, StandardCharsets.UTF_8)
                
                Log.d(TAG, "Received command: $command")
                
                when (command) {
                    "start_sensor" -> startSensorService()
                    "stop_sensor" -> stopSensorService()
                    "export_data" -> exportData()
                    "clear_data" -> clearData()
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "Error handling command", e)
            }
        }
    }

    private fun processSensorData(sensorData: SensorData) {
        // 这里可以添加传感器数据的处理逻辑
        // 例如：保存到本地数据库、发送到云端等
        
        // 发送数据到数据同步服务
        val intent = Intent(this, DataSyncService::class.java).apply {
            action = "SYNC_SENSOR_DATA"
            putExtra("sensor_data", sensorData)
        }
        startService(intent)
    }

    private fun processRecognitionResult(result: String) {
        // 处理识别结果
        // 例如：更新UI、发送通知等
        
        // 广播识别结果
        val intent = Intent("RECOGNITION_RESULT")
        intent.putExtra("result", result)
        sendBroadcast(intent)
    }

    private fun startSensorService() {
        val intent = Intent(this, SensorDataService::class.java)
        startForegroundService(intent)
        Log.d(TAG, "Sensor service started")
    }

    private fun stopSensorService() {
        val intent = Intent(this, SensorDataService::class.java)
        stopService(intent)
        Log.d(TAG, "Sensor service stopped")
    }

    private fun exportData() {
        val intent = Intent(this, DataSyncService::class.java).apply {
            action = "EXPORT_DATA"
        }
        startService(intent)
    }

    private fun clearData() {
        val intent = Intent(this, DataSyncService::class.java).apply {
            action = "CLEAR_DATA"
        }
        startService(intent)
    }

    private fun sendStatus() {
        serviceScope.launch {
            try {
                val status = mapOf(
                    "timestamp" to System.currentTimeMillis(),
                    "sensor_running" to isSensorServiceRunning(),
                    "data_count" to getDataCount()
                )
                
                val statusJson = gson.toJson(status)
                val data = statusJson.toByteArray(StandardCharsets.UTF_8)
                
                val dataMap = PutDataMapRequest.create("/status").apply {
                    dataMap.putByteArray("status", data)
                }.asPutDataRequest()
                
                Wearable.getDataClient(this@WearDataLayerService).putDataItem(dataMap)
                
            } catch (e: Exception) {
                Log.e(TAG, "Error sending status", e)
            }
        }
    }

    private fun isSensorServiceRunning(): Boolean {
        // 检查传感器服务是否运行
        // 这里可以添加实际的检查逻辑
        return true
    }

    private fun getDataCount(): Int {
        // 获取数据数量
        // 这里可以添加实际的统计逻辑
        return 0
    }

    fun sendSensorData(sensorData: SensorData) {
        serviceScope.launch {
            try {
                val dataJson = gson.toJson(sensorData)
                val data = dataJson.toByteArray(StandardCharsets.UTF_8)
                
                val dataMap = PutDataMapRequest.create(SENSOR_DATA_PATH).apply {
                    dataMap.putByteArray("sensor_data", data)
                }.asPutDataRequest()
                
                Wearable.getDataClient(this@WearDataLayerService).putDataItem(dataMap)
                
            } catch (e: Exception) {
                Log.e(TAG, "Error sending sensor data", e)
            }
        }
    }

    fun sendRecognitionResult(result: String) {
        serviceScope.launch {
            try {
                val data = result.toByteArray(StandardCharsets.UTF_8)
                
                val dataMap = PutDataMapRequest.create(RECOGNITION_RESULT_PATH).apply {
                    dataMap.putByteArray("result", data)
                }.asPutDataRequest()
                
                Wearable.getDataClient(this@WearDataLayerService).putDataItem(dataMap)
                
            } catch (e: Exception) {
                Log.e(TAG, "Error sending recognition result", e)
            }
        }
    }
} 